/**
 * 查询给定区域内的地图标注
 *
 * ne 东北(地图右上角)
 * sw 西南(地图左下角)
 * >= sw.lng && <= ne.lng && >= sw.lat && <= ne.lat
 @ResponseBody
 @RequestMapping("map-points")
 public Map<String, Object> getMapPoints(
 @RequestParam("sw.lng") Double swLng,
 @RequestParam("sw.lat") Double swLat,
 @RequestParam("ne.lng") Double neLng,
 @RequestParam("ne.lat") Double neLat
 ) throws IOException {
    Filters filters = Filters.create().ge("longitude", swLng).le("longitude", neLng).ge("latitude", swLat).le("latitude", neLat);
    List<Merchant> merchants = merchantService.findMany(filters, (Sort) null);

    http://developer.baidu.com/map/index.php
 *
 */
window.BdMap = (function () {
	/*
	$.ajax({
		url:'http://api.map.baidu.com/telematics/v3/weather?location=116.30,39.97&output=json&ak=7c5sEdoXPo0jkpdRc4UUYFkm',
	   // url:'http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=7c5sEdoXPo0jkpdRc4UUYFkm',
		dataType:'jsonp',
		success: function(json) {
			console.log(window.json = json);
		}
	});
	*/
	var BMAP_AK = '7c5sEdoXPo0jkpdRc4UUYFkm',
		TIT_PROP = 'companyName', //'title',
		ADDR_PROP = 'address',
		LNG_PROP = 'longitude',
		LAT_PROP = 'latitude',
		contextPath = window.contextPath || '',
		ICON_PATH = contextPath + '/img/map-xiu.png',
		URL = contextPath + '/js/map.json?' + decodeURIComponent(location.search.substring(1)),

		DEFAULT = {
			listContainer: 'poi-list',
			listItemTpl: 'poi-tpl',
			infoBodyTpl: 'info-bd-tpl',
			onRepaint: function (json) {
				var me = this,
					listEls = me._listEls || [],
					len = listEls.length,
					i;

				for (i = 0; i < len; i++) {
					listEls[i].remove();
				}
				me._listEls = [];

				if (!json || 1 > json.length) {
					$('#' + me._config.listContainer).html('<div style="text-align:center;margin-top:100px"><img src="no-result.jpg" width="160"/><p style="color:#a1a1a1;font-size:18px;padding-top">该地区尚无门店</p><p style="color:#a1a1a1;font-size:18px">去其他地方逛逛吧!</p></div>');
				}
			},
			onMarkerAdded: function (marker, poi) {
				var that = this,
					config = that._config,
					list = config.listContainer,
					tpl = config.listItemTpl,
					clone = $('#' + tpl).clone().removeAttr('id').show(),
					listEls = that._listEls || [];

				// 克隆一个模板节点并添加到
				clone.html(fillTpl(clone.html(), poi))
					.appendTo('#' + list)
					.click(function () {
						// marker.dispatchEvent('click');
						that.showInfoWindow(poi);
					});

				listEls.push(clone);
				that._listEls = listEls;
			},
			buildInfoBody: function (poi) {
				// return '<p style="width:280px;margin:0;line-height:20px;">地址：' + poi.address + '</p>';
				var me = this,
					tpl = me.infoBodyTpl,
					clone = $('#' + tpl).clone().removeAttr('id').show();

				// 克隆一个模板节点并添加到
				clone.html(fillTpl(clone.html(), poi));
				return clone[0].outerHTML;
			}
		};

	window.BMap || document.write('<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=' + BMAP_AK + '"></script>');
	if (!window.BMapLib || !window.BMapLib.SearchInfoWindow) {
		document.write('<script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.5/src/SearchInfoWindow_min.js"></script>');
		document.write('<link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.5/src/SearchInfoWindow_min.css"/>');
	}

	function fillTpl(tpl, data) {
		if (!tpl || !data) {
			return tpl;
		}
		for (var p in data) {
			if (data.hasOwnProperty(p)) {
				tpl = tpl.replace(new RegExp('{' + p + '}', 'g'), data[p]);
			}
		}
		return tpl;
	}


	function BdMap(config) {
		var me = this, zoom, center, lng, lat;

		if (!(me instanceof BdMap)) {
			return new BdMap(config);
		}

		config = 'string' === typeof config ? {container: config} : config;
		config = $.extend({}, DEFAULT, config || {});

		config.container = config.container || document.body;
		if ('string' === typeof config.container) {
			config.container = document.getElementById(config.container);
		}

		me._config = config;
		me.params = config.params || {};
		me.init();

		center = config.center;
		zoom = me._config.zoom || 12;

		if (center && (lng = parseFloat(center.lng)) && (lat = parseFloat(center.lat))) {
			me.moveTo(new BMap.Point(lng, lat), zoom);
		} else {
			me.locate(null, zoom);
		}
	}

	BdMap.prototype = {
		init: function () {
			var me = this,
				config = me._config;

			me._map = new BMap.Map(config.container);
			me._map.enableScrollWheelZoom();
			me._map.addControl(new BMap.NavigationControl());   //添加默认缩放平移控件
			me._map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT}));// 左上角，添加比例尺
			me._map.addControl(new BMap.MapTypeControl({anchor: BMAP_ANCHOR_TOP_RIGHT}));

			var proxy = me.repaint.bind(me);

			// me._map.addEventListener('tilesloaded', proxy); // 加载完毕后, 每个图层都会调用, 还是手动调用吧
			me._map.addEventListener('dragend', proxy);     // 拖拽释放后
			me._map.addEventListener('zoomend', proxy);     // 缩放后

			me._map.addEventListener("click", function (e) {
				console.log('click', e.point.lng + "," + e.point.lat, window.point = e.point);
			});
		},
		moveTo: function (point, zoomLevel) {
			var me = this;
			me.centerAndZoom(point, zoomLevel || 12);// 设置中心点坐标和地图级别
			me.repaint();
		},
		/**
		 * 搜索并定位到给定的城市名称
		 * @param city
		 */
		locate: function (city, zoom) {
			var me = this,
				map = me._map,
			// 没有传递位置使用 ip 定位, 传递了使用搜索
				local = !city ? new BMap.LocalCity() : new BMap.LocalSearch(map, {
					onSearchComplete: function (results) {
						var poi = results.getPoi(0);    // 取搜索的第一个结果
						if (undefined != poi) {
							me.moveTo(poi.point, zoom)
						} else {
							console.log('not found', city, window.results = results);
							// TODO
							$('#poi-list').html('<div style="text-align:center;margin-top:100px"><img src="no-result.jpg" width="160"/><p style="color:#a1a1a1;font-size:18px;padding-top">该地区尚无门店</p><p style="color:#a1a1a1;font-size:18px">去其他地方逛逛吧!</p></div>');
						}
					}
				});

			city ? local.search(city) : local.get(function (result) {
				me.moveTo(result.center, zoom || result.level);
			});
		},
		/**
		 * repaint viewport
		 */
		repaint: function () {
			var me = this,
				map = me._map,
				ct = map.getCenter(),
				bounds = map.getBounds(),    // 获取可视范围
				sw = bounds.getSouthWest(),
				ne = bounds.getNorthEast(),
				onRepaint = me._config.onRepaint,
				data = $.extend({}, me.params || {}, {
					'ct.lng': ct.lng,
					'ct.lat': ct.lat,
					'sw.lng': sw.lng,
					'sw.lat': sw.lat,
					'ne.lng': ne.lng,
					'ne.lat': ne.lat
				});

			// TODO
			// clear css
			// $.getJSON(URL, { sw: sw, ne: ne }, function (json) {
			$.ajax({
				url: URL,
				method: 'get',
				data: data,
				dataType: 'json',
				success: function(json) {
					onRepaint.call(me, json, map);

					me.clearPois();
					me.addPois(json);
				}
			});
		},
		/**
		 * 设置/获取缩放
		 * @param zoom
		 */
		zoom: function (zoom) {
			return undefined == zoom ? this._map.getZoom() : this._map.setZoom(zoom);
		},
		/**
		 * 设置中心和缩放
		 */
		centerAndZoom: function () {
			this._map.centerAndZoom.apply(this._map, arguments);
		},
		/**
		 * 清除当前地图上所有点
		 */
		clearPois: function () {
			this._map.clearOverlays();
		},
		addPois: function (pois) {
			var me = this, i;

			pois = pois || [];
			if ('[object Array]' !== Object.prototype.toString.call(pois)) {
				pois = [pois];
			}

			for (i = 0; i < pois.length; i++) {
				me.addPoi(pois[i]);
			}
		},
		addPoi: function (poi) {
			var me = this,
				addr = poi[ADDR_PROP],
				lng = poi[LNG_PROP],
				lat = poi[LAT_PROP];

			// 存在经纬度坐标
			if (null != lng && null != lat) {
				poi.point = new BMap.Point(parseFloat(lng), parseFloat(lat));
				me._addPoi(poi);
			} else {
				// 使用地址解析器解析
				var geo = new BMap.Geocoder();
				geo.getPoint(addr, function (point) {
					if (point) {
						poi.point = point;
						me._addPoi(poi);
					} else {
						window.console && console.log('无法解析地址', addr);
					}
				});
			}
		},
		_addPoi: function (poi) {
			var me = this,
				map = me._map,
				config = me._config,
				marker = new BMap.Marker(poi.point, {
					title: poi[TIT_PROP],
					icon: new BMap.Icon(ICON_PATH, new BMap.Size(18, 27))
				});

			// 添加麻点
			map.addOverlay(marker);
			marker.addEventListener('click', me.showInfoWindow.bind(me, poi));

			config.onMarkerAdded && config.onMarkerAdded.call(me, marker, poi);
		},
		showInfoWindow: function (poi) {
			var me = this,
				config = me._config,
				map = me._map,
				title = poi[TIT_PROP],
				win = new BMapLib.SearchInfoWindow(map, config.buildInfoBody(poi), {
					title: title, //标题
					width: 290, //宽度
					// height: 40, //高度
					panel: "panel", //检索结果面板
					enableSendToPhone: true, //是否显示发送到手机按钮
					searchTypes: [
						// BMAPLIB_TAB_SEARCH,     //周边检索
						// BMAPLIB_TAB_TO_HERE,    //到这里去
						// BMAPLIB_TAB_FROM_HERE   //从这里出发
					]
				});
			win.open(poi.point);
		}
	};

	return BdMap;
})();
